'use server'

import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
import { Decimal } from '@prisma/client/runtime/library'

interface OutboundFormData {
  items: {
    productId: string
    quantity: string
    price: string
  }[]
}

export async function createOutbound(data: OutboundFormData) {
  try {
    // 生成出库单号
    const code = `CK${Date.now()}`
    
    // 计算总金额
    const totalAmount = data.items.reduce((sum, item) => 
      sum + new Decimal(item.price).mul(new Decimal(item.quantity)), 
      new Decimal(0)
    )

    const now = new Date()

    // 开始事务
    const sale = await prisma.$transaction(async (tx) => {
      // 1. 检查库存
      for (const item of data.items) {
        const product = await tx.product.findUnique({
          where: { id: parseInt(item.productId) }
        })

        if (!product) {
          throw new Error(`商品不存在: ${item.productId}`)
        }

        if (product.stock < parseInt(item.quantity)) {
          throw new Error(`商品 ${product.name} 库存不足`)
        }
      }

      // 2. 创建出库单
      const sale = await tx.sale.create({
        data: {
          code,
          totalAmount,
          createdAt: now,
          updatedAt: now,
          items: {
            create: data.items.map(item => ({
              productId: parseInt(item.productId),
              quantity: parseInt(item.quantity),
              price: new Decimal(item.price),
              amount: new Decimal(item.price).mul(new Decimal(item.quantity))
            }))
          }
        },
        include: {
          items: {
            include: {
              product: true
            }
          }
        }
      })

      // 3. 更新商品库存
      for (const item of data.items) {
        await tx.product.update({
          where: { id: parseInt(item.productId) },
          data: {
            stock: {
              decrement: parseInt(item.quantity)
            }
          }
        })
      }

      return sale
    })

    // 序列化返回数据
    const serializedSale = {
      ...sale,
      totalAmount: sale.totalAmount.toString(),
      items: sale.items.map(item => ({
        ...item,
        price: item.price.toString(),
        amount: item.amount.toString(),
        product: {
          ...item.product,
          price: item.product.price.toString()
        }
      }))
    }

    revalidatePath('/dashboard/inventory/outbound')
    return { success: true, data: serializedSale }
  } catch (error) {
    console.error('创建出库单失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '创建出库单失败'
    }
  }
} 